package com.example.upload;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.R.integer;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class UploadAsyncTask extends AsyncTask<Integer, Integer, String> {
	private String mName;// 文件名
	private String mPath;// 文件路径
	private Context mContext;
	private Handler handler;
	private String mUrl = "";// 文件服务器保存文件的url

	/**
	 * 构造方法
	 * 
	 * @param context
	 * @param name
	 * @param path
	 * @param mHandler
	 */
	public UploadAsyncTask(Context context, String name, String path, Handler mHandler) {
		this.mContext = context;
		this.mPath = path;
		this.mName = name;
		this.handler = mHandler;
	}

	@Override
	protected String doInBackground(Integer... arg0) {
		String fileName = mName;// 文件名称
		String filePath = mPath;// 文件路径
		Log.i("Upload", "upload=====name==" + fileName);
		Log.i("Upload", "upload======path==" + filePath);
		boolean sendFlag = true;//
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "******";
		URL url;
		FileInputStream fis = null;
		DataOutputStream dos = null;
		InputStream is = null;
		String result = null;
		try {
			url = new URL(mUrl + fileName);// 最终的路径地址
			HttpURLConnection httpURLConnection = getCon(url); // 创建连接
			dos = new DataOutputStream(httpURLConnection.getOutputStream());
			dos.writeBytes(twoHyphens + boundary + end);
			String str = "Content-Disposition: form-data; name=\"file\"; filename=\""
					+ URLEncoder.encode(fileName, "UTF-8") + "\"" + end;
			dos.writeBytes(str);
			dos.writeBytes(end);

			fis = new FileInputStream(filePath);
			byte[] buffer = new byte[1024 * 4]; // 4k
			int count = 0;
			while ((count = fis.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			fis.close();
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();

			byte[] b = new byte[5000];
			is = httpURLConnection.getInputStream();

			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			result = br.readLine(); // 获取文件服务器返回的结果
			dos.close();
			is.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			Log.d("TAG", "文件上传失败！");

			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					sendFlag = false;
					e.printStackTrace();
				}
			if (dos != null)
				try {
					dos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					sendFlag = false;
					e.printStackTrace();
				}
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					sendFlag = false;
					e.printStackTrace();
				}
		}
		if (sendFlag = false) {
			result = "不成功";
		}
		return result;
	}

	/**
	 * 创建HTTP链接
	 * 
	 * @param url
	 * @return
	 */
	public HttpURLConnection getCon(URL url) {
		String boundary = "******";
		HttpURLConnection httpURLConnection = null;
		try {
			httpURLConnection = (HttpURLConnection) url.openConnection();

			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return httpURLConnection;
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(String result) {
		Message msg = new Message();
		msg.obj = result;
		handler.sendMessage(msg); // 传信息给主线程
		// Toast.makeText(mContext, result, 1).show();
		super.onPostExecute(result);

	}

}
